package org.elanfox.intellicommunity.biz.service.core.msg.impl;

import org.elanfox.intellicommunity.biz.dto.condition.MsgSearchCondition;
import org.elanfox.intellicommunity.biz.dto.msg.MsgSaveDTO;
import org.elanfox.intellicommunity.biz.entity.equipment.CardPO;
import org.elanfox.intellicommunity.biz.entity.equipment.LocatorPO;
import org.elanfox.intellicommunity.biz.entity.msg.MsgBasePO;
import org.elanfox.intellicommunity.biz.entity.msg.MsgBasePO_;
import org.elanfox.intellicommunity.biz.service.core.equipment.CardService;
import org.elanfox.intellicommunity.biz.service.core.equipment.LocatorService;
import org.elanfox.intellicommunity.data.base.base.AbstractSearchableCrudService;
import org.elanfox.intellicommunity.data.base.base.JpaSearchableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author allan
 * @version 1.0.0
 * @date 2019/12/20
 */
public abstract class AbstractMsgService<T, ID extends Serializable> extends AbstractSearchableCrudService<T, ID> {
    @Autowired
    protected LocatorService locatorService;
    @Autowired
    protected CardService cardService;

    protected AbstractMsgService(JpaSearchableRepository<T, ID> repository) {
        super(repository);
    }

    protected Predicate normalPredicates(MsgSearchCondition condition, Root root, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        if (!StringUtils.isEmpty(condition.getUserKey())) {
            predicates.add(cb.like(root.get(MsgBasePO_.realName), likeAll(condition.getUserKey())));
        }
        if (condition.getUserId() > 0) {
            predicates.add(cb.equal(root.get(MsgBasePO_.userId), condition.getUserId()));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

    protected void setMsgField(MsgBasePO msgBasePO, MsgSaveDTO msgSaveDTO, CardPO cardPO) {
        msgBasePO.setStationId(msgSaveDTO.getStationId());
        msgBasePO.setLocatorId(msgSaveDTO.getLocatorId());
        LocatorPO locatorPO = locatorService.findByNo(msgSaveDTO.getLocatorId());
        if (locatorPO == null) {
            return;
        }
        msgBasePO.setLocatorInfo(locatorPO.getLocatorInfo());
        msgBasePO.setCardId(msgSaveDTO.getCardId());
        msgBasePO.setRoomName(cardPO.getUser().getRoomNumber());
        msgBasePO.setUserId(cardPO.getUser().getUserId());
        msgBasePO.setRealName(cardPO.getUser().getName());
        msgBasePO.setUserType(cardPO.getUser().getUserType());
    }
}
